package com.shardingsphere.core.config.shardingsphere;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.hint.HintShardingValue;

import java.util.Collection;
import java.util.HashSet;

/**
 * @author : DaiGD
 * @createtime :  2020年06月13日 16:42
 * @description : 数据库分片策略
 */
@Slf4j
public class MyDatasourceRoutingAlgorithm implements HintShardingAlgorithm<String> {

    /**
     * 用户数据源
     */
    private static final String DB1 = "db1";

    /**
     * 订单数据源
     */
    private static final String DB2 = "db2";

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, HintShardingValue<String> shardingValue) {
        Collection<String> result = new HashSet<>();
        for (String value : shardingValue.getValues()) {
            if (DatasourceType.DB1.toString().equals(value)) {
                if (availableTargetNames.contains(DB1)) {
                    result.add(DB1);
                }
            } else {
                if (availableTargetNames.contains(DB2)) {
                    result.add(DB2);
                }
            }
        }
        log.info("availableTargetNames:{},shardingValue:{},返回的数据源:{}", availableTargetNames, shardingValue, result);
        return result;
    }
}

